<template>
  <view class="washer-dryer-view">
    <ProgramControl
      :control="baseControl"
      :flex-area-links="flexAreaLinks"
      :custom-state-getter="customStateGetter"
      @adjust="openAdjustParameter"
    >
      <template #aside-control>
        <AsideControl
          :control="baseControl"
          :role="AsideRoles.Power"
          :overwrites="powerControlOverwrites"
          :prevent="control.store.shouldConfirmShutdown"
          @power-change="onPowerChange"
        />
      </template>

      <AdjustParameterModal
        v-model:show="adjustParameterVisible"
        :control="baseControl"
        :custom-params="customParams"
      />
      <OrderModal v-model:show="orderModalVisible" :control="baseControl" :custom-params="customParams" />
      <StainModal v-model:show="stainModalVisible" :control="control" />
      <ShutdownTips v-model:show="showShutdownTips" :control="control" @confirm="confirmShutdown" />
    </ProgramControl>

    <!-- 固件升级成功 -->
    <SuccessAcknowledge v-if="otaHelper" :helper="otaHelper" />
  </view>
</template>

<script setup lang="ts">
import ProgramControl from '../view/control/programControl.vue'
import type { FlexAreaLink } from '../view/control/components/FlexArea.vue'
import OrderModal from '../view/order/index.vue'
import AdjustParameterModal from '../view/adjustParameterModal.vue'
import { useI18n } from 'vue-i18n'
import type { BaseController } from '@/controller/BaseAppliance/definition'
import type { CustomOption } from '../components/parameterCard.vue'
import { AsideRoles, useControlState } from '@/controller/BaseAppliance/useControl'
import AsideControl from '../view/control/components/AsideControl.vue'
import { OPERATION_STATES, WASHER_STAINS, WASHER_STAINS_OFF } from '@/constants/Command'
import StainModal from './stains/stainModal.vue'
import { onceObserve, toPage } from '@/utils/mpHelper'
import type { WasherDryerController } from '@/controller/WasherDryer/definition'
import { useShutdown } from '../view/powerShutdown/useShutdown'
import ShutdownTips from '../view/powerShutdown/shutdownTips.vue'
import { checkApplianceRelatedFlexAreaAccessable } from '@/controller/common/ErrorHandler/validator'
import SuccessAcknowledge from '../settings/ota/modals/successAcknowledge.vue'
import { useInhouseOtaHelper } from '../view/useOtaHelper'
import type { CustomConfigGetter, StateViewConfig } from '../view/stateView.vue'

const props = defineProps<{
  control: WasherDryerController.Control
}>()

const i18n = useI18n()

const control = props.control
const { store } = control
const baseControl = control as BaseController.Control
const { isOffline, orderDisabled } = useControlState(control)

/**
 * OTA升级
 */
const otaHelper = useInhouseOtaHelper(control)

/**
 * 断电处理
 */
const { powerControlOverwrites, onPowerChange, showShutdownTips, confirmShutdown } = useShutdown(control)

/**
 * 智能除渍
 */
const stainModalVisible = ref(false)
function openStainModal() {
  stainModalVisible.value = true
}

/**
 * Flex Area Links
 */
const flexAreaLinks = computed(() => {
  if (!store._datasource.loaded) return []

  const links: FlexAreaLink[] = [
    {
      icon: '/pages/appliance/static/DelayStart.png',
      name: i18n.t('Appliance.OrderWash.Button.Text'),
      trackCode: '',
      disabled: isOffline.value === true,
      plainDisabled: orderDisabled.value,
      onClick: () => checkApplianceRelatedFlexAreaAccessable(props.control) && openOrderModal(),
    },
    {
      icon: '/pages/appliance/static/Consumable.png',
      name: i18n.t('Appliance.ConsumablesService.Button.Text'),
      trackCode: '',
      onClick: openConsumablesService,
    },
  ]
  return links
})

/**
 * 跳转耗材服务
 */
function openConsumablesService() {
  toPage('/pages/consumablesService/consumablesService', {
    vib: store._datasource.vib,
  })
}

/**
 * 调节参数
 */
const adjustParameterVisible = ref(false)
const customParams: CustomOption[] = [
  {
    key: WASHER_STAINS,
    hasArrow: true,
    isActive(value) {
      return value !== WASHER_STAINS_OFF
    },
    getLabel(value, option) {
      const currentOption = option.customOption?.options?.find((option) => option.value === value)
      if (currentOption?.value === WASHER_STAINS_OFF) return option.label

      return currentOption?.label || option.label
    },
    onClick: openStainModal,
  },
]
function openAdjustParameter() {
  adjustParameterVisible.value = true
}

/**
 * 预约
 */
const orderModalVisible = ref(false)
function openOrderModal() {
  orderModalVisible.value = true
}

/**
 * 免排水
 */
const rinseHoldActived = ref(false)
watch(
  () => props.control.store.isRinseHoldPresent,
  async (isRinseHoldPresent) => {
    /**
     * Present 时、或Off时已不在ActionRequired状态时  同步Present状态到Active状态
     */
    if (isRinseHoldPresent || props.control.store.operationState !== OPERATION_STATES.ACTION_REQUIRED) {
      rinseHoldActived.value = isRinseHoldPresent
      return
    }

    // Acknowledge后，当OperationState切换后，再同步Present状态
    await onceObserve(() => props.control.store.operationState)
    rinseHoldActived.value = isRinseHoldPresent
  }
)
const customStateGetter: CustomConfigGetter = (currentState, defaultGetter) => {
  if (rinseHoldActived.value) {
    // 免排水使用 已暂停视图 去除操作按钮
    const config: StateViewConfig = defaultGetter(OPERATION_STATES.PAUSE)
    config.actions = []
    return config
  }

  return defaultGetter(currentState)
}
</script>
